package codingforgreat.class22;

public class Class02_TrappingRainWater {
    public int trap(int[] height) {
        if (height == null || height.length < 2) {
            return 0;
        }
        int N = height.length;
        int L = 1;
        int R = N - 2;
        int Lmax = height[0];
        int Rmax = height[N - 1];
        int water = 0;
        while(L <= R){
            if(Lmax <= Rmax){
                water += Math.max(0,(Lmax - height[L]));
                Lmax = Math.max(Lmax, height[L++]);
            }else{
                water += Math.max(0,(Rmax - height[R]));
                Rmax = Math.max(Rmax, height[R--]);
            }
        }
        return water;
    }
}
